<template>
  <div id="role-manager">
    <!--主页面头-->
    <v-header class="pa-left15" title="角色管理" :showDownloadBtn="false" :saveShow="false"></v-header>
    <!--主页面内容-->
    <div class="role-container-wrap">
      <el-container>
        <el-header height="58px">
          <el-row class="toolbar">
            <el-button type="primary" size="mini" @click="addRoleBtnClick">增加</el-button>
            <el-button type="primary" size="mini" @click="deleteRolesData">删除</el-button>
            <el-button type="primary" size="mini" @click="refreshRolesData">刷新</el-button>
            <el-button type="primary" size="mini" @click="allotTableBtnClick" v-show="showAllotTableBtn">分配</el-button>
            <!--<el-button type="primary" size="mini">分配业务系统</el-button>-->
          </el-row>
        </el-header>
        <el-main style="margin-bottom: 20px">
          <el-row>
            <el-col :span="showAllotTableBtn ? 24 : 16" class="tablePanel">
              <role-grid ref="roleGrid">
                <template slot="extendEndSlot">
                  <el-table-column
                    label="操作"
                    width="300">
                    <template slot-scope="scope">
                      <el-button @click="editRolBtnClick(scope.row)" type="text" size="small">编辑</el-button>
                      <el-button @click="deleteRolesData([scope.row])" type="text" size="small">删除</el-button>
                      <!--
                          查看分配和清空树选择遇到一个问题，el-tree的node-key不能配置为obj.id,要解决这个问题那只有重新封装后台TreeNode
                      -->
                      <!--<el-button v-show="attachPanelShow" type="text" size="small">查看分配</el-button>-->
                    </template>
                  </el-table-column>
                </template>
              </role-grid>
            </el-col>
            <el-col :span="showAllotTableBtn ? 0 : 8" class="attach-panel">
              <transition name="fade">
                <div v-show="attachPanelShow">
                  <div class="toolbar">
                    <el-button type="primary" size="mini" @click="cancelAllotBtnClick">取消</el-button>
                  </div>
                  <el-collapse accordion>
                    <el-collapse-item title="分配菜单" name="allotMenu">
                      <menu-tree :default-expand-all="false" ref="attachMenuTree">
                      <!--  <template slot="toolbar">
                          <el-button type="primary" size="mini" @click="allotMenuBtnClick">确认分配</el-button>
                        </template>-->
                      </menu-tree>
                      <el-row class="mt10 ml10">
                        <el-button type="primary" size="mini" @click="allotMenuBtnClick">确认分配</el-button>
                        <!--<el-button type="primary" size="mini" @click="resetAllotMenuClick">清空选择</el-button>-->
                      </el-row>
                    </el-collapse-item>
                    <el-collapse-item title="分配用户" name="allotUser">
                      <user-grid ref="attachUserGrid"></user-grid>
                      <el-row class="mt10 ml10">
                        <el-button type="primary" size="mini" @click="allotUserBtnClick">确认分配</el-button>
                        <!--<el-button type="primary" size="mini" @click="allotUserBtnClick">清空选择</el-button>-->
                      </el-row>
                    </el-collapse-item>
                  </el-collapse>
                </div>
              </transition>
            </el-col>
          </el-row>
        </el-main>
      </el-container>
    </div>
    <!--下面放弹出的内容-->
    <template>
      <!--参照DdataBoard.vue中的新增看板-->
      <el-dialog
        :title="addRoleDialogMode == 'ADD' ? '新增角色' : '编辑角色'"
        :visible.sync="addRoleDialogVisiable"
        v-model="addRoleDialogMode"
        @close="ardCancelBtnClick"
        width="422px">
        <el-form :model="addFormData"
                 :rules="rules"
                 ref="addForm"
                 label-width="100px"
                 :label-position="'right'">
          <el-form-item label="名称" prop="name">
            <el-input v-model="addFormData.name" placeholder="请在此输入"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="remark">
            <el-input v-model="addFormData.remark" placeholder="请在此输入"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="resetForm('addForm')" class="dialog-btn">重置</el-button>
            <el-button @click="ardCancelBtnClick" class="dialog-btn">关闭</el-button>
            <el-button @click="submitRole" type="primary" class="dialog-btn">确定</el-button>
        </span>
      </el-dialog>
    </template>
  </div>
</template>

<script type="text/ecmascript-6">
import {VHeader} from '../../../components'
import ajax from '../../../api/ajax/ajax'
import Msg from '../../../assets/js/msg'
import api from '../../../api/url'
import menuTree from './menuTree'
import roleGrid from './roleGrid'
import UserGrid from './userGrid'

export default {
  components: {
    UserGrid,
    roleGrid,
    menuTree,
    VHeader
  },
  name: 'role-manager',
  data () {
    return {
      showAllotTableBtn: true, // 是否显示分配按钮
      addRoleDialogMode: { // 对话框色对话框模式  ADD新增 MODIFY 修改
        type: String,
        default: 'ADD'
      },
      addRoleDialogVisiable: false, // 新增角色对话框显示控制
      currentItem: {
        name: null,
        remark: null
      }, // 表单初始化数据
      addFormData: { // 新增角色对话框表单数据
        name: '',
        remark: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 1, max: 16, message: '长度在 1 到 16 个字符', trigger: 'blur' }
        ]
      },
      attachPanelShow: false // 附属面板是否显示
    }
  },
  methods: {
    // 奇偶行角色表格显示
    roleTableRowClassName ({row, rowIndex}) {
      return rowIndex % 2 === 0 ? 'warning-row' : 'success-row'
    },
    // 新增角色按钮
    addRoleBtnClick () {
      // 显示新增角色对话框
      this.addRoleDialogVisiable = true
      // 新增角色对话框模式
      this.addRoleDialogMode = 'ADD'

      // 表单数据初始化
      this.currentItem = {
        name: null,
        remark: null
      }
      this.addFormData = {...this.currentItem}
    },
    // 编辑角色按钮
    editRolBtnClick (role) {
      // 显示新增角色对话框
      this.addRoleDialogVisiable = true
      // 新增角色对话框模式 编辑模式
      this.addRoleDialogMode = 'MODIFY'
      // 当前选中数据
      this.currentItem = role
      this.addFormData = {...this.currentItem}
    },
    // 新增角色或修改角色
    submitRole () {
      this.$refs.addForm.validate((valid) => { // 校验表单验证情况
        if (valid) {
          const postUrl = this.addRoleDialogMode === 'ADD' ? api.ADDSYSROLE : api.MODIFYSYSROLE
          ajax.post(postUrl, this.addFormData).then(res => {
            // 刷新数据
            this.refreshRolesData()
            // 隐藏新增对话框
            this.addRoleDialogVisiable = false
            // 数据清空
            setTimeout(() => {
              this.resetForm('addForm')
            }, 200)
          }).catch(e => {
            console.error('新增角色数据发生错误！')
          })
        } else {
          return false
        }
      })
    },
    // 删除角色数据
    deleteRolesData (selection) {
      let selectionRecords = []
      let selectionRecordsObj = this.$refs.roleGrid.getSelectionRecords()
      selectionRecords.push(selectionRecordsObj)
      let postData = selectionRecords
      if (selection.length) {
        postData = selection
      }
      if (postData.length < 1) {
        this.$message.error('请选择一条记录进行删除')
      } else {
        Msg.confirm('确定删除选中的角色记录吗？（同时会删除与该角色关联的用户角色关系）', {
          onConfirm: () => {
            ajax.post(api.DELSYSROLE, postData).then(res => {
              // 刷新数据
              this.refreshRolesData()
            }).catch(e => {
              console.error('删除角色数据发生错误！')
            })
          },
          onCancel () {

          }
        })
      }
    },
    // 刷新角色数据
    refreshRolesData () {
      this.$refs.roleGrid.getAllRolesData()
    },
    // 取消新增
    ardCancelBtnClick () {
      this.addRoleDialogVisiable = false
      // 清空数据
      this.addFormData = {}
      // 清除验证
      this.$refs.addForm.clearValidate()
    },
    // 重置表单
    resetForm (formName) {
      this.addFormData = {...this.currentItem}
      // 清除验证
      this.$refs.addForm.clearValidate()
    },
    // 表格分配按钮
    allotTableBtnClick () {
      let selectedRole = this.$refs.roleGrid.getSelectionRecords()
      if (selectedRole.length < 1) {
        this.$message.error('请至少选择一条角色记录进行分配')
        return
      }
      // 显示附属面板
      this.attachPanelShow = true
      // 隐藏分配按钮
      this.showAllotTableBtn = false
    },
    // 取消分配按钮
    cancelAllotBtnClick () {
      // 隐藏附属面板
      this.attachPanelShow = false
      // 显示分配按钮
      this.showAllotTableBtn = true
    },
    // 分配菜单按钮
    allotMenuBtnClick () {
      let selectedRole = []
      let selectedRoleObj = this.$refs.roleGrid.getSelectionRecords()
          selectedRole.push(selectedRoleObj)
//      if (selectedRole.length > 1) { 单选不需要次判断
//        this.$message.error('请至少选择一条角色记录进行分配')
//        return
//      }
      let selectedMenu = this.$refs.attachMenuTree.getCheckedMenuTreeNodes()
      if (!selectedMenu.length) {
        this.$message.error('请至少选择一项菜单记录')
        return
      }
      // 菜单项和角色进行混合
      let roleMenuList = []
      for (let role of selectedRole) {
        for (let menu of selectedMenu) {
          roleMenuList.push({
            menuId: menu.id,
            roleId: role.id,
            sysNo: menu.sysNo
          })
        }
      }
      // 为角色分配菜单,提交数据
      ajax.post(api.ROLEASSIGNMENU, {
        roleMenuList
      }).then(res => {
        if (res.msg === '交易成功') {
          this.cancelAllotBtnClick()
        }
        this.$message({
          type: 'success',
          message: '角色分配菜单成功!'
        })
      }).catch(e => {
        console.error('角色分配菜单发生错误！')
      })
    },
    // 分配用户按钮
    allotUserBtnClick () {
      // 当前选中的角色
      let selectedRole = []
      let selectedRoleObj = this.$refs.roleGrid.getSelectionRecords()
      selectedRole.push(selectedRoleObj)
      if (!selectedRole.length) {
        this.$message.error('请至少选择一条角色记录进行分配')
      } else {
        // 当前选中的用户
        let selectedUser = this.$refs.attachUserGrid.getSelectionRecords()
        if (!selectedUser.length) {
          this.$message.error('请至少选择一条用户记录进行分配!')
        } else {
          // 为角色分配用户,提交数据
          let userRoleList = []
          for (let role of selectedRole) {
            for (let user of selectedUser) {
              userRoleList.push({
                userId: user.id,
                roleId: role.id
              })
            }
          }
          ajax.post(api.ROLEASSIGNUSER, {
              userRoles: userRoleList
          }).then(res => {
          if (res.msg === '交易成功') {
              this.cancelAllotBtnClick()
             }
            // this.$message.info('角色分配用户成功!')
            this.$message({
              type: 'success',
              message: '角色分配用户成功!'
            })
          }).catch(e => {
            console.error('角色分配用户发生错误!')
          })
        }
      }
    }
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus">
#role-manager
  overflow hidden
  font-size 14px
  height 100%
  .pa-left15
    padding-left 15px
  .role-container-wrap
    overflow auto
    height calc(100% - 56px)
    margin 10px 0 0 10px
  .el-container
    .el-header
      padding 0 0
      .toolbar
        height 50px
        line-height 50px
        vertical-align middle
        background-color #fff
        padding 0 15px
    .el-main
      padding 0 0
      .tablePanel
        padding-right 10px
      .warning-row
        background rgba(218, 225, 253, 0.55)
      .success-row
        background rgba(218, 225, 253, 0.85)
      .attach-panel
        height 100%
        background-color #fff
        .toolbar
          height 40px
          line-height 40px
          vertical-align middle
          button
            margin-left 10px
        .el-collapse-item__header
          padding 0 10px

</style>
